import random
import re

from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.views.generic.base import View
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection

from carts.utils import merge_cart
from meiduo_mall.utils import meiduo_signature
from meiduo_mall.utils.response_code import RETCODE

# 请求QQ授权
from oauth import constants
from oauth.models import OAuthQQUser
from users.models import User


class OauthQQUrlView(View):
    def get(self, request):
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.GET.get('next')
        # 初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        # 获取QQ登录扫码页面，扫码后得到AuthorizationCode
        login_url = oauth.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})


# QQ授权回调
class QQAuthUserView(View):
    """用户扫码登录的回调处理"""

    def get(self, request):
        """Oauth2.0认证"""
        # 接收Authorization Code
        code = request.GET.get('code')
        state = request.GET.get('state', '/')
        if not code:
            return http.HttpResponseForbidden('缺少code')
        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        # 1.根据code获取token
        token = oauth.get_access_token(code)

        # 2.根据token获取openid
        openid = oauth.get_open_id(token)

        # 判断是否初次授权
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未查到数据，则为初次授权，显示绑定页面
            # 将openi加密
            json_str = meiduo_signature.dumps({"openid": openid}, constants.OPENID_EXPIRES)
            # 显示绑定页面
            context = {
                'token': json_str
            }
            return render(request, 'oauth_callback.html', context)
        else:
            # 查询到授权对象，则状态保持，转到相关页面
            user = qquser.user
            login(request, user)

            response = redirect(state)
            response.set_cookie('username', user.username)
            return response

    def post(self, request):
        # 接收：openid,mobile,password,sms_code
        access_token = request.POST.get('access_token')
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        pic_code = request.POST.get('pic_code')
        sms_code = request.POST.get('sms_code')
        state = request.GET.get('state', '/')

        # 验证注册参数
        openid_dict = meiduo_signature.loads(access_token, constants.OPENID_EXPIRES)
        if openid_dict is None:
            return http.HttpResponseForbidden('openid无效，请重新填写openid')
        openid = openid_dict.get('openid')
        # 处理：初次授权，完成openid与user的绑定
        # 1.判断手机号是否已经使用
        try:
            user = User.objects.get(mobile=mobile)
        except:
            # 如果未使用，则新建用户
            user = User.objects.create_user(mobile, password=password, mobile=mobile)
        else:
            # 如果已使用，则验证密码
            # 密码正确，则继续执行
            if not user.check_password(password):
                return http.HttpResponseForbidden('手机号已使用，或密码错误')

            # 绑定 ： 新建QAuthUser对象

        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )
        # 状态保持
        login(request, user)
        response = redirect(state)
        # 合并购物车
        response = merge_cart(request, response)
        return response
